<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="./css/detail.css">
    <script src="./js/promiseajax.js"></script>
    <script src="./js/cookie.js"></script>
</head>

<body>
    <div class="listtitle">详情页</div>
    <div class="top">
        <div class="enlarge">

        </div>
        <div class="goods">

        </div>
        <button class="addcart">加入购物车</button>
        <button onclick="location.href='tocart.html'">去购物车结算</button>
    </div>

    <div class="bottom">

    </div>
</body>
<script>
    // 获取当前商品的id - 从地址栏中获取商品id
    var reg = /id=([^&]+)/
    var arr = location.search.match(reg)
    console.log(arr);
    if (arr && arr[1]) {
        var id = arr[1]
    }
    // 发请求获取商品详细信息
    var enlarge = document.querySelector('.enlarge')
    var goods = document.querySelector('.goods')
    var bottom = document.querySelector('.bottom')
    request({
        url: '/api/goods/goodsDetail/' + id
    }).then(res => {
        console.log(res);
        enlarge.innerHTML = '<img class="d1" src="' + res.data.data.img_big_logo + '" />'
        goods.innerHTML = `
        <p>${res.data.data.title}</p>
        <p>${res.data.data.price}</p>
    `
        bottom.innerHTML = res.data.data.goods_introduce

        // 加入购物车
        cart()
    })

    function cart() {
        document.querySelector('.addcart').onclick = function () {
            // 判断用户是否登录
            var username = getCookie('username')
            if (!username) {
                alert('请先登录')
                // 将当前地址存起来
                localStorage.setItem('url', location.href)
                location.href = '/login.html'
                return false
            }
            // 登录成功
            // 添加购物车，本质就是将当前商品数据存储下来，到购物车页面的时候获取出来展示
            request({
                url: '/api/cart/addcart',
                method: 'post',
                data: {
                    goodsid: id,
                    goodsnumber: 1,
                    userid: getCookie('userid')
                }
            }).then(res => {
                // 响应
                // console.log(res);
                var { error_code, msg } = res
                alert(msg)

            })
        }
    }

</script>

</html>